package appapi.service.impl;

import appapi.Global.BusinessException;
import appapi.Request.OperPageReq;
import appapi.dao.CertificateMapper;
import appapi.dao.OperatorMapper;
import appapi.dao.ProjectMapper;
import appapi.dao.StaffMapper;
import appapi.dto.DelOperDto;
import appapi.entity.Zhongjiao.CertificateDto;
import appapi.entity.Zhongjiao.OperatorDto;
import appapi.entity.Zhongjiao.ProjectDto;
import appapi.service.IOperatorService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author djq
 * @date 2023/5/12 15:27
 * @description:
 */
@Component
public class OperatorService implements IOperatorService {
    @Resource
    private OperatorMapper operatorMapper;
    @Resource
    private CertificateMapper certificateMapper;
    @Resource
    ProjectMapper projectMapper;
    @Resource
    StaffMapper staffMapper;


    @Override
    public List<Map<String, Object>> SelectOperatorPage(OperPageReq operPageReq) {
        PageHelper.startPage(operPageReq.getCurrPage(), operPageReq.getPageSize());

        List<Map<String, Object>> operPageList = operatorMapper.selectOperPageList(operPageReq);

        return operPageList;
    }

    @Override
    public Map<String, Object> SelectOperatorDetail(Long operId) {

        Map<String, Object> operDetail = operatorMapper.selectOperDetail(operId);
        if (operDetail != null) {
            //取出组织机构路径
            List<Long> orgaPathIds = Arrays.stream(operDetail.get("orgaPathIds").toString().split("-")).map(map -> (Long.parseLong(map.trim()))).collect(Collectors.toList());
            operDetail.put("orgaArr", orgaPathIds);
            //operPageList.forEach((map)->{
            List<CertificateDto> certificates = certificateMapper.selectAllByOperId((Long) operDetail.get("operId"));
            certificates.forEach(map -> {
                List<Long> arr = new ArrayList<>();
                arr.add(map.getOperTypeId());
                arr.add(map.getOperItemId());
                map.setOperItemIdArr(arr);
            });

            operDetail.put("certificates", certificates);
            //});

        }

        return operDetail;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void InsertOperator(OperatorDto operatorDto) {
        if (operatorMapper.selectByIdCard(operatorDto.getOperCardId()) != null) {
            throw new BusinessException(500, "该人员已存在!");
        }
        //判断该账号是否在管理员也存在
        Map<String, Object> staffAccount = staffMapper.selectMobile(operatorDto.getOperMobile());
        if (staffAccount!=null) {
            throw new BusinessException(500, "手机号已使用!");
        }
        //获取项目组织机构id
        ProjectDto projectDto = getProject(operatorDto);
        //验证当前项目人员是否存在
         int iRet=operatorMapper.selectCountByMobileAndProjId(operatorDto.getOperMobile(),projectDto.getProjId());
         if(iRet>0)
         {
             throw new BusinessException(500, "手机号重复，不能添加!");
         }


//      if (staffAccount!=null) {
//            operatorDto.setWxId(staffAccount.get("staffWxid").toString());
//      }
        operatorDto.setCreateTime(LocalDateTime.now());
        operatorDto.setUpdateTime(LocalDateTime.now());
        operatorDto.setProjid(projectDto.getProjId());
        operatorDto.setOperAuditState(2);
        operatorMapper.insertSelective(operatorDto);
        if (operatorDto.getCertificates()!=null){
            //增加人员证书
            insertCertificate(operatorDto);
        }
    }

    private ProjectDto getProject(OperatorDto operatorDto) {
        List<ProjectDto> projectDto = projectMapper.selectByProjectByOrgaId(operatorDto.getOrgaId());
        if (projectDto.size()==0){
            throw new BusinessException(-1,"该项目不存在或已被删除!");
        }
        return projectDto.get(0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void UpdateOperator(OperatorDto operatorDto) {
        if (operatorMapper.selectByPrimaryKey(operatorDto.getOperId()) == null)
            throw new BusinessException(500, "该人员不存在或已被删除!");

        ProjectDto projectDto = getProject(operatorDto);

        operatorDto.setProjid(projectDto.getProjId());
        operatorDto.setOperAuditState(2);
        operatorMapper.updateByPrimaryKeySelective(operatorDto);

        certificateMapper.deleteByOperId(operatorDto.getOperId());
        //先删除再增加增加人员证书
        //增加人员证书
        if (operatorDto.getCertificates()!=null){
            //增加人员证书
            insertCertificate(operatorDto);
        }
    }

    private void insertCertificate(OperatorDto operatorDto) {
        List<CertificateDto> collect = operatorDto.getCertificates().stream().map((certificate) -> {
            CertificateDto dto = new CertificateDto();
            BeanUtils.copyProperties(certificate,dto);
            dto.setOperId(operatorDto.getOperId());
            dto.setCertificateCtime(LocalDateTime.now());
            //certificateMapper.insertSelective(certificate);
            return dto;
        }).collect(Collectors.toList());
        if (collect.size()>0) {
            certificateMapper.insertList(collect);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void DelOperator(DelOperDto dto) {
//        if (operatorMapper.selectByPrimaryKey(operId) == null)
//            throw new BusinessException(500, "该人员不存在或已被删除!");

        operatorMapper.deleteByIds(dto.getOperIds());

        dto.getOperIds().forEach(map -> certificateMapper.deleteByOperId(map));
        //删除其证书

    }

    @Override
    public List<OperatorDto> SelectOperatorList(OperPageReq operPageReq) {

        List<Long> operId = null;
        if (operPageReq.getOperItemId() != null) {
            List<CertificateDto> certificateDtos = certificateMapper.selectAllByOperItemId(operPageReq.getOperItemId());
            operId = certificateDtos.stream().map(CertificateDto::getOperId).collect(Collectors.toList());
        }

        List<OperatorDto> operPageList = operatorMapper.selectOperList(operPageReq.getProjId(), operPageReq.getOperName(), operId,operPageReq.getOperItemId());
        //计算年龄
        for (OperatorDto dto : operPageList) {
            LocalDateTime birthday = dto.getOperBirthday();
            LocalDate from = LocalDate.from(birthday);
            int age = LocalDate.now().getYear() - from.getYear();
            dto.setOperAge(age);
        }
        operPageList.forEach(map -> {
            //查到该设备下所有人员的准操作项目并拼接为字符串
            List<CertificateDto> operIds = certificateMapper.selectAllByOperId(map.getOperId());
            String items = operIds.stream().map(CertificateDto::getOperItemName).collect(Collectors.joining(","));

            map.setItemName(items);
        });

        return operPageList;
    }
}
